import 'package:sqflite/sqflite.dart';

extension IterableExt<E> on Iterable<E> {
  Future<List<E>> asyncFilter(Future<bool> Function(E current) test) async {
    List<E> result = [];
    for (int i = 0; i < length; i++) {
      E item = elementAt(i);
      if (await test(item)) {
        result.add(item);
      }
    }
    return result;
  }

  List<E> distinct(bool Function(List<E> result, E current) repeat) {
    List<E> result = [];
    forEach((element) {
      if (!repeat(result, element)) result.add(element);
    });
    return result;
  }

  List<E> separator(E element) {
    List<E> result = [];
    Iterator<E> iterator = this.iterator;
    if (iterator.moveNext()) {
      result.add(iterator.current);
      while (iterator.moveNext()) {
        result.add(element);
        result.add(iterator.current);
      }
    }
    return result;
  }

  E? find(bool Function(E element) test) {
    E? result;
    for (E element in this) {
      if (test(element)) {
        result = element;
        break;
      }
    }
    return result;
  }
}

extension DatabaseExceptionExt on DatabaseException {
  bool isForeignKeyConstraintError() => toString().contains('FOREIGN KEY constraint failed');
}
